<?php 

namespace app\api\controller\v1;

use app\api\model\WXBizDataCrypt;
use app\api\model\Consumer as ConsumerModel;
use app\api\service\AppToken;
use app\api\service\ConsumerToken;
use app\api\validate\AppTokenGet;
use app\api\validate\TokenGet;
use app\api\service\UserToken;
use app\api\validate\TokenInviteGet;
use app\lib\exception\FailMessage;
use app\lib\exception\ParameterException;
use app\api\service\Token as TokenService;
use app\api\validate\UserPhone;
use app\lib\exception\SuccessMessage;
use think\Db;

class Token
{
    // 获取token
	public function getToken($code = '')
	{
		(new TokenGet())->goCheck();
		$ut = new UserToken($code);
		$result = $ut->get();

		// return [
		// 	'token' => $token
		// ];

		return $result;
	}

	// 测试
    public function testToken($account='', $pass='')
    {
        (new TokenGet())->goCheck();

        $ut = new UserToken('test');

        $token = $ut->testGet();
        $result = [
            'msg' => 'success',
            'error_code' => 0,
            'token' => $token
        ];

        return $result;
    }

	// 更新用户的数据 (head_id,dealer_id,type)
    public function inviteToken($head_id='', $type='')
    {
        (new TokenInviteGet())->goCheck();
        $uid = TokenService::getCurrentUid();

        // 更新用户数据
        $data = ConsumerModel::updateInfo($uid,$head_id,$type);

        $result = [];
        $result['msg'] = 'success';
        $result['error_code'] = 0;
        $result['data'] = $data;

        return $result;

    }

	// 校验token
	public function verifyToken($token='')
	{
		if(!$token){
			throw new ParameterException([
				'msg'=>'token不允许为空'
			]);
		}
		$valid = TokenService::verifyToken($token);
		$result = [];

		if($valid){
            $result['code'] = 1;
            $result['msg'] = 'success';
            $result['data'] = '';
        }else{
            $result['code'] = 0;
            $result['msg'] = 'error';
            $result['data'] = '';
        }

		return $result;
	}

	/*
	 * 第三方应用获取令牌(cms)
	 * @url /app_token?
	 * @POST ac=:ac se=:secret
	 */
	public function getAppToken($ac='', $se='')
	{
		(new AppTokenGet())->goCheck();

		$app = new AppToken();
		$token = $app->get($ac, $se);

		return [
			'token' => $token
		];
	}

	/*
		解密用户手机号,并更新昵称,头像
	*/
	public function getUserPhone()
	{
        $validate = new UserPhone();
        $validate->gocheck();

        $WxData = $validate->getDataByRule(input('post.'));

        $session_key = TokenService::getCurrentTokenVar('session_key');

        $pc = new WXBizDataCrypt(config('wx.app_id'), $session_key);
        $errCode = $pc->decryptData($WxData["encryptedData"], $WxData["iv"], $data );

        if ($errCode == 0) {
            $user_info = json_decode($data, true);
//            $result = ConsumerToken::get($user_info);
            $uid = TokenService::getCurrentUid();
            $update_data['wechatname'] = $WxData['wechatname'];
            $update_data['headavatar'] = $WxData['headavatar'];
            $update_data['phone'] = $user_info['phoneNumber'];
            $update = Db::name('consumer')->where('id',$uid)->update($update_data);

            if ($update !== false){
                return new SuccessMessage();
            }else{
                return new FailMessage();
            }
        } else {
            return new FailMessage();
        }
	}
}